package com.code.qgjx.controller.dealcontroller;

import com.alibaba.fastjson.JSON;
import com.code.qgjx.entity.StudentJob;
import com.code.qgjx.entity.User;
import com.code.qgjx.service.StudentJobService;
import com.code.qgjx.service.UserService;
import com.code.qgjx.tools.EmailUtil;
import com.code.qgjx.tools.Layui;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/Sys")
@Api("学生岗位管理相关api")
@Slf4j
public class StudentJobController {

    @Autowired
    private StudentJobService studentJobService;
    @Autowired
    private UserService userService;
    @Autowired
    private EmailUtil emailUtil;

    /**
     * 获取学生岗位列表
     *
     * @param limit 每页记录数
     * @param page  页码
     * @return 返回学生岗位列表的JSON字符串
     */
    @RequestMapping("/getStudentJobList")
    @ResponseBody
    public String getStudentJobList(@RequestParam("limit") String limit, @RequestParam("page") String page) {
        int lim = Integer.parseInt(limit);
        int start = (Integer.parseInt(page) - 1) * lim;
        List<StudentJob> studentJobs = studentJobService.getAllStudentJobsWithPage(start, lim);
        int total = studentJobService.getStudentJobCount();
        return JSON.toJSONString(Layui.data(total, studentJobs));
    }

    /**
     * 获取带有详细信息的学生岗位列表
     *
     * @param userId 用户ID，可选参数
     * @param limit 每页记录数
     * @param page  页码
     * @param departmentName 部门名称，可选参数
     * @param status 岗位状态，可选参数
     * @return 返回带有详细信息的学生岗位列表的JSON字符串
     */
    @RequestMapping("/getStudentJobs")
    @ResponseBody
    public String getStudentJobs(@RequestParam(value = "userId", required = false) Long userId,
                                @RequestParam("limit") String limit,
                                @RequestParam("page") String page,
                                @RequestParam(value = "departmentName", required = false) String departmentName,
                                @RequestParam(value = "status", required = false) Integer status) {
        int lim = Integer.parseInt(limit);
        int start = (Integer.parseInt(page) - 1) * lim;

        List<Map<String, Object>> studentJobs = studentJobService.getStudentJobsWithDetails(userId, start, lim, departmentName, status);
        int total = studentJobService.getStudentJobCountWithDetails(userId, departmentName, status);

        return JSON.toJSONString(Layui.data(total, studentJobs));
    }

    /**
     * 添加学生岗位申请
     *
     * @param map 包含用户ID和岗位ID的Map对象
     * @return 返回添加结果，"success"或"failure"
     */
    @RequestMapping("/addStudentJob")
    @ResponseBody
    public String addStudentJob(@RequestBody Map<String, Object> map) {
        StudentJob studentJob = new StudentJob();
        studentJob.setUserId(Long.parseLong(map.get("userId").toString()));
        studentJob.setJobPositionId(Long.parseLong(map.get("jobPositionId").toString()));
        boolean b = studentJobService.applyJob(studentJob);
        User user = userService.getUserById(studentJob.getUserId());
        // 异步发送邮件通知
        if (user.getMessagePush() != null && user.getMessagePush() && user.getEmail() != null) {
            emailUtil.sendSimpleMail(
                    user.getEmail(),
                    "工作申请",
                    "有学生申请了岗位，请审批"
            );
        }
        return b ? "success" : "failure";
    }

    /**
     * 学生退出岗位
     *
     * @param userId 用户ID
     * @param jobPositionId 岗位ID
     * @return 返回退出结果，"success"或"failure"
     */
    @RequestMapping("/quitStudentJob")
    @ResponseBody
    public String quitStudentJob(@RequestParam("userId") Long userId, @RequestParam("jobPositionId") Long jobPositionId) {
        return studentJobService.quitJob(userId, jobPositionId) ? "success" : "failure";
    }

    /**
     * 获取岗位下的学生列表
     *
     * @param jobPositionId 岗位ID
     * @param limit 每页记录数
     * @param page  页码
     * @return 返回岗位下学生列表的JSON字符串
     */
    @RequestMapping("/getJobStudents")
    @ResponseBody
    public String getJobStudents(@RequestParam("jobPositionId") Long jobPositionId,
                                @RequestParam("limit") String limit,
                                @RequestParam("page") String page) {
        int lim = Integer.parseInt(limit);
        int start = (Integer.parseInt(page) - 1) * lim;
        List<StudentJob> studentJobs = studentJobService.getJobStudentsWithPage(jobPositionId, start, lim);
        int total = studentJobService.getStudentJobCountByJobPositionId(jobPositionId);
        return JSON.toJSONString(Layui.data(total, studentJobs));
    }

    /**
     * 根据状态获取学生岗位列表
     *
     * @param status 岗位状态
     * @param limit 每页记录数
     * @param page  页码
     * @return 返回根据状态筛选的学生岗位列表的JSON字符串
     */
    @RequestMapping("/getStudentJobsByStatus")
    @ResponseBody
    public String getStudentJobsByStatus(@RequestParam("status") Integer status,
                                        @RequestParam("limit") String limit,
                                        @RequestParam("page") String page) {
        int lim = Integer.parseInt(limit);
        int start = (Integer.parseInt(page) - 1) * lim;
        List<StudentJob> studentJobs = studentJobService.getStudentJobsByStatusWithPage(status, start, lim);
        int total = studentJobService.getStudentJobCountByStatus(status);
        return JSON.toJSONString(Layui.data(total, studentJobs));
    }

    /**
     * 获取特定学生和岗位的信息
     *
     * @param userId 用户ID
     * @param jobPositionId 岗位ID
     * @return 返回学生岗位信息的JSON字符串，如果找不到则返回null
     */
    @RequestMapping("/getStudentJob")
    @ResponseBody
    public String getStudentJob(@RequestParam("userId") Long userId, @RequestParam("jobPositionId") Long jobPositionId) {
        StudentJob studentJob = studentJobService.getStudentJob(userId, jobPositionId);
        return studentJob != null ? JSON.toJSONString(studentJob) : null;
    }

    /**
     * 更新学生岗位状态
     *
     * @param params 包含用户ID、岗位ID和状态的Map对象
     * @return 返回更新结果，"success"或"failure"
     */
    @PostMapping("/updateStudentJobStatus")
    @ResponseBody
    public String updateStudentJobStatus(@RequestBody Map<String, Object> params) {
        try {
            StudentJob studentJob = new StudentJob();
            studentJob.setUserId(Long.parseLong(params.get("userId").toString()));
            studentJob.setJobPositionId(Long.parseLong(params.get("jobPositionId").toString()));
            studentJob.setStatus(Integer.parseInt(params.get("status").toString()));

            User user = userService.getUserById(studentJob.getUserId());
            boolean success = studentJobService.updateJobStatus(studentJob);

            // 异步发送邮件通知
            if (user.getMessagePush() != null && user.getMessagePush() && user.getEmail() != null) {
                if (studentJob.getStatus() == -1) {
                    emailUtil.sendSimpleMail(
                        user.getEmail(),
                        "岗位申请被驳回通知",
                        "很抱歉，您的岗位申请被驳回"
                    );
                } else if (studentJob.getStatus() == 1) {
                    emailUtil.sendSimpleMail(
                        user.getEmail(),
                        "岗位申请通过通知",
                        "恭喜！您的岗位申请已通过审核。"
                    );
                }
            }

            return success ? "success" : "failure";
        } catch (Exception e) {
            return "failure";
        }
    }
}
